package club.yunqiang.arithmetic.sort;

import java.util.Arrays;

import club.yunqiang.arithmetic.sort.model.Student;

/**
 * @author YunQiang
 */
public class SelectionSort {

	/**
	 * 私有化构造器，使算法不产生任何实例
	 */
	private SelectionSort() {
	}

	/**
	 * 选择排序
	 *
	 * @param comparables
	 */
	@SuppressWarnings("unchecked")
	public static void sort(@SuppressWarnings("rawtypes") Comparable[] comparables) {
		for (int i = 0; i < comparables.length; i++) {
			int minObjectIndex = i;
			// 选出最小对象的下标
			for (int j = i; j < comparables.length; j++) {
				// 对象为空不做操作
				if (comparables[j] != null && comparables[minObjectIndex] != null) {
					if (comparables[j].compareTo(comparables[minObjectIndex]) < 0) {
						minObjectIndex = j;
					}
				}
			}
			// 将i所指下标下的对象和剩余最小对象交换
			swap(comparables, i, minObjectIndex);
		}
	}
	
	/**
	 * 交换数组中的两个对象
	 *
	 * @param array数组
	 * @param i数组下标
	 * @param j数组下标
	 */
	private static void swap(Object[] array, int i, int j) {
		Object temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	public static void main(String[] args) {
		
		// 01 选择排序 - 数字
		Integer[] numbers = SortTestHelper.generateRandomArray(10000, 1, 10);
		SelectionSort.sort(numbers);
		System.out.println(Arrays.toString(numbers));

		// 02 选择排序 - 对象
		Student[] students = new Student[7];
		students[0] = new Student("zhang1", 60);
		students[1] = new Student("zhang2", 60);
		students[2] = new Student("zhang3", 30);
		students[3] = new Student("zhang4", 60);
		students[4] = new Student("zhang5", 60);
		students[5] = new Student("zhang6", 80);
		students[6] = new Student("zhang7", 60);

		SelectionSort.sort(students);
		System.out.println(Arrays.toString(students));
		
		SortTestHelper.testSort(SelectionSort.class.getName(), SortTestHelper.generateRandomArray(10000000, 1, 1000000));
		
		return;
	}

}
